<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import * as echarts from 'echarts';
import { getStatistics3API } from '@/api';
import { useResizeObserver } from '@vueuse/core'
const current = ref('week')
const options = [
  {
    text: '近一个月',
    value: 'month'
  },
  {
    text: '近一周',
    value: 'week'
  },
  {
    text: '近24小时',
    value: 'hour'
  },

]
const handleChoose = (type) => {
  current.value = type
  getData()
}
var myChart = null
onMounted(() => {
  var chartDom = document.getElementById('chart');
  // 如果用户有权限就渲染节点
  if (chartDom) {
    myChart = echarts.init(chartDom)
    getData()
  }

})
onBeforeUnmount(() => {
  // 防止打包之后白屏
  if (myChart) {
    echarts.dispose(myChart)
  }
})
// 获取柱状图的数据
const getData = async () => {

  let option = {
    xAxis: {
      type: 'category',
      data: []
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        data: [],
        type: 'bar'
      }
    ]
  };

  // option && myChart.setOption(option);
  myChart.showLoading()
  const res = await getStatistics3API(current.value)
  // console.log(res);
  option.xAxis.data = res.x
  option.series[0].data = res.y
  myChart.setOption(option);
  myChart.hideLoading()
}
const el = ref(null)

// 页面变化时使柱状图自适应
useResizeObserver(el, (entries) => {
  myChart.resize()
})
</script>
<template>
  <el-card shadow="never">
    <template #header>
      <div class="flex justify-between">
        <span class="text-sm">订单统计</span>
        <div>
          <el-check-tag v-for="(item, index) in options" :key="index" :checked="current === item.value"
            style="margin-right: 8px" @click="handleChoose(item.value)">
            {{ item.text }}
          </el-check-tag>
        </div>
      </div>
    </template>
    <!-- card body -->
    <div ref="el" id="chart" style="width: 100%; height: 300px;"></div>
  </el-card>

</template>